//
//  SSComposeViewController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/28.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SVProgressHUD

private let titleViewHeight: CGFloat = 36
private let toolbarHeight: CGFloat = 44
private let maxContentLength = 140
class SSComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func loadView() {
        super.loadView()
        view.backgroundColor = UIColor.whiteColor()
        automaticallyAdjustsScrollViewInsets = false
        prepareNavBar()
        // 先添加TextView再添加ToolBar， 因为TextView的layout为fill
        prepareTextView()
        prepareFotoSelectorView()
        prepareToolBar()
        prepareIndicator()
        addKeyboardObserver()
    }
    
    deinit {
        removeKeyboardObserver()
    }
    
    func addKeyboardObserver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardPushed:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    func removeKeyboardObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func keyboardPushed(notify: NSNotification) {
//        print(notify)
        let animDuration = notify.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let rect = notify.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        self.toolbarBottomCons?.constant = -(view.bounds.height - rect.origin.y)
        
        UIView.animateWithDuration(animDuration) { () -> Void in
//            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
            self.view.layoutIfNeeded()
        }
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textview.becomeFirstResponder()
    }
    
    private func prepareIndicator() {
        indicator.color = UIColor.darkGrayColor()
        view.addSubview(indicator)
        indicator.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: view, size: nil)
    }
    
    private func prepareFotoSelectorView() {
        view.addSubview(fotoVC.view)
        addChildViewController(fotoVC)
        
        var size = UIScreen.mainScreen().bounds.size
        size.height = size.height * 0.6
        fotoVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: size)
    }
    
    private func prepareTextView() {
        
        view.addSubview(textview)

        textview.ff_Fill(view, insets: UIEdgeInsets(top: 64, left: 0, bottom: 44, right: 0))
        textview.delegate = self
        textview.addSubview(placeholder)
        placeholder.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textview, size: nil, offset: CGPoint(x: 5, y: 8))
        automaticallyAdjustsScrollViewInsets = false
    }
    
    private var toolbarBottomCons: NSLayoutConstraint?
    
    private func prepareToolBar() {
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        for dict in itemSettings {

            items.append(UIBarButtonItem(target: self, imageName: dict["imageName"]!, actionName: dict["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        
        view.addSubview(toolbar)
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: toolbarHeight))
        
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
//        print(toolbarBottomCons?.constant)
        
        view.addSubview(contentLengthHintLabel)
        contentLengthHintLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil, offset: CGPoint(x: -5, y: -5))
    }
    
    private func prepareNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "post")
        navigationItem.rightBarButtonItem?.enabled = false
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: titleViewHeight))
        navigationItem.titleView = view
        
        let topLabel = UILabel(fontColor: UIColor.darkGrayColor(), fontSize: 15)
        topLabel.textAlignment = NSTextAlignment.Center
        topLabel.text = "发微博"
        topLabel.sizeToFit()
        
        let bottomLabel = UILabel(fontColor: UIColor.lightGrayColor(), fontSize: 13)
        bottomLabel.textAlignment = NSTextAlignment.Center
        bottomLabel.text = SSUserToken.loadToken()?.userInfo.name ?? ""
        bottomLabel.sizeToFit()
        
        view.addSubview(topLabel)
        view.addSubview(bottomLabel)
        topLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: view, size: nil)
        bottomLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: nil)
    }
    
    func inputEmoticon() {
        print("表情亮了")
        removeKeyboardObserver()
        textview.resignFirstResponder()
        
        textview.inputView = (textview.inputView != emoticonVC.view) ? emoticonVC.view : nil
        addKeyboardObserver()
        textview.becomeFirstResponder()
        
    }
    
    func close() {
        textview.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func post() {
//        print(textview.emoticonText)
        if textview.text.characters.count > maxContentLength {
            SVProgressHUD.showInfoWithStatus("文字内容过长", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        // 只能发一张
        let image = fotoVC.images.last ?? nil
//        SVProgressHUD.showInfoWithStatus("正在发送中...", maskType: SVProgressHUDMaskType.Black)
        indicator.startAnimating()
        SSNetworkTools.sharedNetworkTools.postStatus(textview.emoticonText, image: image) { (result, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
                return
            }
            print(result)
            self.close()
            self.indicator.stopAnimating()
            SVProgressHUD.showInfoWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
        }
    }
    
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
    private lazy var fotoVC = SSFotoSelectorCollectionViewController()
    private lazy var contentLengthHintLabel: UILabel = {
        let lbl = UILabel(fontColor: UIColor.lightGrayColor(), fontSize: 12)
        lbl.text = "\(maxContentLength)"
        lbl.sizeToFit()
        return lbl
    }()
    private lazy var emoticonVC: SSEmoticonViewController = SSEmoticonViewController { [weak self] (emoticon) -> Void in
        // TODO: 进入表情键盘时定位到第二个
        self?.textview.showSelectedEmoticon(emoticon)
    }
    private lazy var toolbar = UIToolbar()
    private lazy var textview: UITextView = {
        let view = UITextView()
        view.font = UIFont.systemFontOfSize(18)
        view.alwaysBounceVertical = true
        view.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return view
        }()
    private lazy var placeholder: UILabel = {
        let placeholder = UILabel(fontColor: UIColor.lightGrayColor(), fontSize: 18)
        placeholder.text = "分享新鲜事..."
        placeholder.textColor = UIColor.lightGrayColor()
        placeholder.sizeToFit()
        return placeholder
    }()
}

extension SSComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
//        print(textview.attributedText)
        placeholder.hidden = textview.hasText()
        navigationItem.rightBarButtonItem?.enabled = textview.hasText()
        let currentCharacterCount = textview.text.characters.count
        contentLengthHintLabel.textColor = currentCharacterCount > maxContentLength ? UIColor.redColor() : UIColor.lightGrayColor()
        contentLengthHintLabel.text = "\(maxContentLength - currentCharacterCount)"
    }
    
    
}
